package com.xzl.serviceribbon;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    ConsulClient client;


    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name, String token) throws JsonProcessingException, InterruptedException {
        String url = "http://SERVICE-HI/hiya?name=" + name;
        restTemplate.getForObject("http://SERVICE-HI/hiya?name=" + name, String.class);
        Map body = new HashMap();
        body.put("num", 100);
        Thread.sleep(3000);
        return "";
    }

    public String hiError(String name, String token) {
        return "";
    }

    public String deregist(String id) {
        if (client == null)
            client = new ConsulClient("127.0.0.1", 8500);
        client.agentServiceDeregister(id);
        return null;
    }

    public String regist(String id) {
        NewService newService = new NewService();
        newService.setId(id);
        newService.setName(id+"-name");
        newService.setTags(Arrays.asList("EU-West", "EU-East"));
        newService.setPort(8771);

        NewService.Check serviceCheck = new NewService.Check();
        serviceCheck.setHttp("http://127.0.0.1:8782/health");
        serviceCheck.setInterval("10s");
        newService.setCheck(serviceCheck);
        client.agentServiceRegister(newService);
        return null;
    }
}
